package org.six11.util.gui;

import java.awt.geom.Rectangle2D;
import java.awt.geom.Point2D;

import org.six11.util.Debug;

/**
 * A handy class for determining the bounding box of 2D objects--just
 * give it some points and it will give you the bounding box. This
 * class is only necessary because the Java Rectangle classes include
 * the origin in the rectangle by default, which isn't what we want at
 * all.
 **/
public class BoundingBox {
  boolean hasX = false;
  double minX;
  double maxX;

  boolean hasY = false;
  double minY;
  double maxY;

  public double getX() {
    if (!hasX) bug("There's no real x value yet!");
    return minX;
  }

  public double getWidth() {
    if (!hasX) bug("There's no real x value yet!");
    return maxX - minX;
  }

  public double getY() {
    if (!hasY) bug("There's no real y value yet!");
    return minY;
  }

  public double getHeight() {
    if (!hasY) bug("There's no real y value yet!");
    return maxY - minY;
  }

  public double getDiagonal() {
    return Math.hypot(getWidth(), getHeight());
  }

  public void add(Rectangle2D rec) {
    add(new Point2D.Double(rec.getX(), rec.getY()));
    add(new Point2D.Double(rec.getX()+rec.getWidth(), rec.getY()+rec.getHeight()));
  }

  public void add(Point2D pt) {
    if (!hasX) {
      maxX = pt.getX();
      minX = maxX;
      hasX = true;
    } else {
      maxX = Math.max(maxX, pt.getX());
      minX = Math.min(minX, pt.getX());
    }

    if (!hasY) {
      maxY = pt.getY();
      minY = maxY;
      hasY = true;
    } else {
      maxY = Math.max(maxY, pt.getY());
      minY = Math.min(minY, pt.getY());
    }
  }

  public Rectangle2D getRectangle() {
    return new Rectangle2D.Double(getX(), getY(), getWidth(), getHeight());
  }

  public void bug(String what) {
    Debug.out("BoundingBox", what);
  }

}
